import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter_rtk/api/api.dart';
import 'package:flutter_rtk/common/assets.dart';
import 'package:flutter_rtk/common/common.dart';
import 'package:flutter_rtk/common/config.dart';
import 'package:flutter_rtk/common/constants.dart';
import 'package:flutter_rtk/components/refresh_list_widget.dart';
import 'package:flutter_rtk/entities/undo_page_entity.dart';
import 'package:flutter_rtk/router/index.dart';
import 'package:flutter_rtk/service/store_service.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class MyTodoPage extends StatefulWidget {
  const MyTodoPage({super.key});

  @override
  State<MyTodoPage> createState() => _MyTodoPageState();
}

class _MyTodoPageState extends State<MyTodoPage> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  int _currentIdx = 0;
  final List _tabs = ["待处理", "已处理", "我发起的"];
  final List _actions = ["undo", "done", "launch"];

  final Map<String, UndoPageEntity?> _result = {};

  _buildMainView() {
    return Scaffold(
      appBar: mainAppBar(
        title: "我的待办",
        bottomWidget: TabBar(
          labelColor: AppConstants.brandColor,
          unselectedLabelColor: Colors.black,
          indicatorColor: Colors.transparent,
          controller: _tabController,
          tabs: _tabs.map((e) => Tab(key: ValueKey(e), child: _buildTabHeader(e))).toList(),
          onTap: (idx) {
            if (idx == _currentIdx) {
              return;
            }
            setState(() {
              _currentIdx = idx;
            });
            _fetchTodoList(
              action: _actions[_currentIdx],
              callback: (entity) {
                setState(() {
                  _result[_actions[_currentIdx]] = entity;
                });
              },
            );
          },
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        physics: const NeverScrollableScrollPhysics(),
        children: [
          _result[_actions[0]] != null ? _buildUndoContent(_result[_actions[0]]!) : const Center(child: Text("Loading...")),
          _result[_actions[1]] != null ? _buildUndoContent(_result[_actions[1]]!) : const Center(child: Text("Loading...")),
          _result[_actions[2]] != null ? _buildUndoContent(_result[_actions[2]]!) : const Center(child: Text("Loading...")),
        ],
      ),
    );
  }

  _buildUndoContent(UndoPageEntity? taskInfo) {
    if (taskInfo == null) {
      return const Center(child: Text("信息加载中"));
    }
    return Container(
      width: double.infinity,
      height: 405.h * 3,
      alignment: Alignment.center,
      child: Scrollbar(
        child: taskInfo.records.isEmpty
            ? const Center(child: Text("暂无数据"))
            : RefreshListWidget(
                itemBuilder: (item) {
                  return Padding(
                    padding: EdgeInsets.only(left: 25.w, right: 25.w, top: 25.h),
                    child: _buildTodoItem(item),
                  );
                },
                separatorBuilder: (idx) => const SizedBox.shrink(),
                dataList: taskInfo.records,
                onRefresh: () => _fetchTodoList(
                  action: _actions[_currentIdx],
                  current: 1,
                  callback: (UndoPageEntity entity) {
                    setState(() {
                      _result[_actions[_currentIdx]] = entity;
                    });
                  },
                ),
                onLoading: taskInfo.current < taskInfo.pages
                    ? () => _fetchTodoList(
                          action: _actions[_currentIdx],
                          current: taskInfo.current + 1,
                          callback: (UndoPageEntity entity) {
                            setState(() {
                              UndoPageEntity oldEntity = _result[_actions[_currentIdx]] as UndoPageEntity;
                              entity.records.insertAll(0, oldEntity.records);
                              _result[_actions[_currentIdx]] = entity;
                            });
                          },
                        )
                    : null,
              ),
      ),
    );
  }

  Widget _buildTabHeader(e) {
    String selectedTxt = _tabs[_currentIdx];
    if (e == selectedTxt) {
      return Text(e, style: TextStyle(color: AppConstants.brandColor, fontSize: 30.sp, fontWeight: FontWeight.w500));
    }
    return Text(e, style: TextStyle(color: const Color(0xFF666666), fontSize: 30.sp, fontWeight: FontWeight.w500));
  }

  /// width: 710.w, height: 380.h,margin: EdgeInsets.only(top: 25.h)
  Widget _buildTodoItem(UndoItem item) {
    return InkWell(
      onTap: () {
        if (item.sourceCode == "SEP" || item.sourceCode == "CIP") {
          String token = StoreService.to.getString(AppConstants.token);
          if (token.startsWith("bearer ")) {
            token = token.substring(7);
          }
          String url = "${AppConfig.homeTodoCIPPrefixDomain}?token=$token&url=${Uri.encodeComponent(item.targetMobileUrl.replaceAll("&amp;", "&"))}&type=workflow&sourceCode=${item.sourceCode}&thirdInsId=${item.thirdInsId}&thirdTaskId=${item.thirdTaskId}&showAppbar=1";
          log(url);
          Navigator.pushNamed(context, AppRouters.webview, arguments: {"title": item.title, "url": url});
        } else if (item.sourceCode == "EPC") {
          String token = StoreService.to.getString(AppConstants.token);
          if (token.startsWith("bearer ")) {
            token = token.substring(7);
          }
          String url = "${AppConfig.homeTodoEPCPrefixDomain}?Sinoma_Auth=$token&redirect=${Uri.encodeComponent(item.targetMobileUrl.replaceAll("&amp;", "&"))}&showAppbar=1";
          Navigator.pushNamed(context, AppRouters.webview, arguments: {"title": item.title, "url": url});
        } else {
          showToast("功能未开放,请联系管理员");
        }
      },
      child: Stack(children: [
        Container(
          width: 710.w,
          height: 380.h,
          padding: EdgeInsets.symmetric(horizontal: 40.w, vertical: 30.h),
          decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(10.r)),
          child: Column(mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: [
            Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
              SizedBox(width: 30.w, height: 34.h, child: Image.asset(AppAssets.mineAboutUs)),
              SizedBox(width: 25.w),
              Expanded(
                child: Text(
                  item.title,
                  style: TextStyle(fontSize: 30.sp, fontWeight: FontWeight.w600, color: const Color(0xFF333333)),
                  maxLines: 4,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              // FittedBox(child: Text("发起人:张三", style: TextStyle(fontSize: 24.sp, color: const Color(0xFF999999), fontWeight: FontWeight.w500))),
            ]),
            _buildText("发送时间\u0020:\u0020", item.startDate.substring(0, 10)),
            _buildText("项目名称\u0020:\u0020", item.projectName, maxLines: 3),
            _buildText("发\u0020\u0020送\u0020人\u0020:\u0020", item.startUserName),
            _buildText("备\u0020\u0020\u0020\u0020\u0020\u0020\u0020注\u0020:\u0020", item.remark),
          ]),
        ),
        _currentIdx == 1 ? Positioned(top: 36.h, right: 48.w, child: Image.asset(AppAssets.undoTicket, width: 110.w, height: 96.h)) : const SizedBox.shrink(),
      ]),
    );
  }

  _buildText(String label, String value, {int maxLines = 1}) {
    return Row(mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [
      SizedBox(width: 130.w, height: 40.h, child: Text(label, style: TextStyle(fontSize: 28.sp, fontWeight: FontWeight.w500, color: const Color(0xFF999999), height: 1), textAlign: TextAlign.end)),
      SizedBox(width: 10.w),
      Expanded(child: Text(value, style: TextStyle(fontSize: 28.sp, fontWeight: FontWeight.w500, color: const Color(0xFF999999), height: 1), maxLines: maxLines)),
    ]);
  }

  @override
  Widget build(BuildContext context) {
    return _buildMainView();
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this);
    _fetchTodoList(
      action: _actions[_currentIdx],
      callback: (entity) {
        setState(() {
          _result[_actions[_currentIdx]] = entity;
        });
      },
    );
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  _fetchTodoList({required String action, required Function callback, int current = 1}) async {
    try {
      UndoPageEntity entity = await AppApi.getUndoPage(action: action, current: current);
      callback(entity);
      return entity.records;
    } catch (e) {
      debugPrint("获取待办任务列表失败: $e");
      showToast("获取待办任务列表失败:$e");
    }
    return [];
  }
}
